package com.zzw.junit5demo.extension;

import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.InvocationInterceptor;
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @author zzw
 * @version 1.0
 * @title InterceptorExtension
 * @description <description class purpose>
 * @datetime 2023-06-16 22:35
 */
public class InterceptorExtension implements InvocationInterceptor {

    // 该拦截方法仅对 @Test 注解的测试方法有效
    @Override
    public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
                             ExtensionContext extensionContext) throws Throwable {
        List<Object> reList = invocationContext.getArguments();
        // 获取参数，通过判断参数继续执行还是跳过。实际上不能对拦截的方法进行任何的修改操作
        if(reList.size() == 1 && (Integer)reList.get(0) < 1){
            try {
                invocation.proceed();
            }catch (Throwable e) {
                System.out.println("发生了异常");
            }
        } else{
            // 跳过
            System.out.println("参数小于1，跳过测试执行");
            invocation.skip();
        }
    }
}
